//
//  BankCardVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/12.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "BankCardVC.h"
#import "TopBackView.h"
#import "AddBankCardVC.h"
#import "Common.h"
#import "BankCardModel.h"
#import "BankCardCell.h"
#import "WKProgressHUD.h"
#import "SetPasswordVC.h"
#import "PasswordView.h"


@interface BankCardVC ()<UITableViewDelegate,UITableViewDataSource,PasswordViewDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArr;

@property (nonatomic,strong) UIView *alphaView;
@property (nonatomic,strong) NSString *checkString;
@property (nonatomic) NSInteger number;
@property (nonatomic,strong) WKProgressHUD *hud;


@end

@implementation BankCardVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _number = 0;
    self.dataArr = [NSMutableArray array];

    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"银行卡"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    [self initDataSource];
    [self initVSubViews];
    
    self.alphaView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];


}

-(void)initDataSource
{
    [Common requestWithUrlString:bankcard_list contentType:application_json finished:^(id responseObj) {
        
        
        if (self.dataArr.count > 0) {
            [self.dataArr removeAllObjects];
        }
        
        
        if ([responseObj[@"success"] boolValue] ) {
            
            if ([responseObj[@"data"] count] > 0) {
                
                for (NSDictionary *dic in responseObj[@"data"]) {
                    BankCardModel *model = [[BankCardModel alloc]init];
                    [model  setValuesForKeysWithDictionary:dic];
                    
                    [self.dataArr addObject:model];
                }
               
            }
            [self.tableView reloadData];

            
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(void)initVSubViews
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight + cellHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.tableView];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (self.dataArr.count > 0) ? self.dataArr.count : 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *string = @"tradeCell";
    BankCardCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"BankCardCell" owner:nil options:nil].lastObject;
    }
    cell.contentView.backgroundColor = GrayColor;
//    cell.backView.backgroundColor = Color_RGB(12, 156, 240, 1);
    
    if (self.dataArr.count > 0) {
        
        cell.model = self.dataArr[indexPath.row];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 105;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}



-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, cellHeight)];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, screenWidth, cellHeight);
    [button addTarget:self action:@selector(addBankCard) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(18, CGRectGetMidY(view.frame) - 6.5, 13, 13)];
    imageV.image = [UIImage imageNamed:@"wallet_icon_bankcard_add "];
    [view addSubview:imageV];

    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageV.frame) + 2, 0, 100, cellHeight)];
    label.text = @"添加银行卡";
    label.textColor = littleBlackColor;
    label.font = Font(14);
    [view addSubview:label];
    
    UIImageView *imageV1 = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth - 24, CGRectGetMidY(view.frame) - 5.5, 6.5, 11)];
    imageV1.image = [UIImage imageNamed:@"personal_arrow"];
    [view addSubview:imageV1];
    
    view.backgroundColor = WhiteColor;
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _number = indexPath.row + 1;
    
    [self showAlertController];
    
    
}

-(void)showAlertController
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"解绑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self initAlphaViewAndString:@"为了您的帐户安全，请输入您的提现密码"];

        
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}


//解绑银行卡
-(void)unbundlingBankCard
{
    
    BankCardModel *model = [[BankCardModel alloc]init];
    model = self.dataArr[_number -1];
    NSDictionary *dic = @{@"cardId":model.Id,
                          @"cashPwd":self.checkString};
    
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:unbind_bankcard parms:dic finishedBlock:^(id responseObj) {
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [WKProgressHUD popMessage:dictionary[@"message"] inView:self.view duration:1.5 animated:YES];

        if ([dictionary[@"data"] boolValue]) {
            
            [self initDataSource];
        }
        
        
    } failedBlock:^(NSString *errorMsg) {
        
    }];
}



-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addBankCard
{
    _number = 0;
    //先判断是否设置提现密码
    [self checkPWD];
    
  }

-(void)checkPWD
{
    [Common requestWithUrlString:exist_pwd contentType:application_json finished:^(id responseObj) {
        
        [self.hud dismiss:YES];
        
        if ([responseObj[@"data"] boolValue]) {
            
            [self initAlphaViewAndString:@"为了您的帐户安全，请输入您的提现密码"];
            
        } else {
            
            
            //未设置密码 先去设置密码
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                SetPasswordVC *set = [[SetPasswordVC alloc]init];
                [self.navigationController pushViewController:set animated:YES];
                
            });
            
           
            
        }
        
    } failed:^(NSString *errorMsg) {
        
        [self.hud dismiss:YES];
        NSLog(@"%@",errorMsg);
    }];
}

-(void)initAlphaViewAndString:(NSString *)string
{
    
    self.alphaView.backgroundColor = RGBACOLOR(0, 0, 0, 0.3);
    self.alphaView.alpha = 1;
    //    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    //    [window addSubview:self.alphaView];
    
    [self.view addSubview:self.alphaView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToDismiss)];
    [self.alphaView addGestureRecognizer:tap];
    
    UIView *whiteV = [[UIView alloc]initWithFrame:CGRectMake(20, 110 * kHeight, screenWidth - 40, 140)];
    whiteV.backgroundColor = WhiteColor;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 25, screenWidth - 80, 15)];
    label.textColor = YellowColor;
    label.text = string;
    label.font = Font(12);
    [whiteV addSubview:label];
    
    PasswordView *password = [[PasswordView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(label.frame) + 20, screenWidth - 80, cellHeight)];
    [whiteV addSubview:password];
    password.layer.borderColor = LineGrayColor.CGColor;
    password.layer.borderWidth = 0.5;
    password.delegate = self;
    password.backgroundColor = WhiteColor;
    
    [self.alphaView addSubview:whiteV];
    
    
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [whiteV.layer addAnimation:animation forKey:nil];
    
    
}

-(void)tapToDismiss{
    
    [UIView animateWithDuration:0.2 animations:^{
        [self.alphaView endEditing:YES];
        
        self.alphaView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.alphaView removeFromSuperview];
    }];
}

#pragma mark PasswordView Delegate
-(void)passWordDidChange:(PasswordView *)password
{
    NSLog(@"改变%@",password.textStore);
}

-(void)passWordBeginInput:(PasswordView *)password
{
    NSLog(@"开始输入%@",password.textStore);
}

-(void)passWordCompleteInput:(PasswordView *)password
{
    NSLog(@"输入完成%@",password.textStore);
    
    if (password.textStore.length == 6 ) {
        
        self.checkString = password.textStore;
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

            [self checkPassword];
            
            
        });
    }
    
    
//    if (password.textStore.length == 6 && self.integer == 2) {
//        
//        self.updateString = password.textStore;
//        //延迟执行
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            
//            [self updatePassword];
//            
//            
//        });
//    }
    
}

//验证原始密码
-(void)checkPassword
{
    __weak typeof (self) weakSelf = self;
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:check_pwd parms:@{@"pwd":self.checkString} finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [self.hud dismiss:YES];
        
        if (_number > 0) {
            //解绑银行卡
            if ([dic[@"success"] boolValue]) {
                
                [self tapToDismiss];

                [self unbundlingBankCard];
                
            } else {
                
                
                [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
                
                [weakSelf initAlphaViewAndString:@"请输入提现密码"];
            }
            
            
        } else {
            
            if ([dic[@"success"] boolValue]) {
                
                AddBankCardVC *addVC = [[AddBankCardVC alloc]init];
                addVC.pwdString = self.checkString;
                
                [self tapToDismiss];
                
                [self.navigationController pushViewController:addVC animated:YES];
                
                
            } else {
                
                [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
                
                [weakSelf initAlphaViewAndString:@"请输入提现密码"];
                
            }

        }
        
        
        
    } failedBlock:^(NSString *errorMsg) {
        
        [self.hud dismiss:YES];
        NSLog(@"%@",errorMsg);
    }];
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return cellHeight;
}

-(void)viewWillAppear:(BOOL)animated
{
    [self initDataSource];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
